/** eslint-disable */
{
    // ES3,ES5 数据保护
    class Person {
        constructor() {
            var data = {
                name: 'es3',
                sex: 'male',
                age: 15
            };
            this.get = function (key) {
                return data[key];
            };
            this.set = function (key, value) {
                if (key !== 'sex') {
                    data[key] = value;
                }
            };
        }
    }
    var person = new Person();
    // 数据读取
    console.table({ name: person.get('name'), sex: person.get('sex'), age: person.get('age') });
    // 修改
    person.set('name', 'es3-cname');
    console.table({ name: person.get('name'), sex: person.get('sex'), age: person.get('age') });
    person.set('sex', 'female');
    console.table({ name: person.get('name'), sex: person.get('sex'), age: person.get('age') });
}

{
    // ES5
    var Person = {
        name: 'es5',
        age: 15
    }
    Object.defineProperty(Person, 'sex', {
        writable: false,
        value: 'male'
    })

    console.table({ name: Person.name, age: Person.age, sex: Person.sex });
    Person.name = 'es5-cname';
    console.table({ name: Person.name, age: Person.age, sex: Person.sex });
    try {
        Person.sex = 'female';
        console.table({ name: Person.name, age: Person.age, sex: Person.sex });
    } catch (error) {
        console.log(error);
    }
}

{
    // ES6
    let Person = {
        name: 'es6',
        sex: 'male',
        age: 15
    }

    let person = new Proxy(Person, {
        get(target, key) {
            return target[key]
        },
        set(target, key, value) {
            if (key !== 'sex') {
                target[key] = value
            }
        }
    })
    console.table({ name: person.name, sex: person.sex, age: person.age });

    try {
        person.sex = 'female';
    } catch (error) {
        console.log(error);
    }

    const phoneHandle = {
        set(target, key, value) {
            target[key] = value.match(/[0-9]/g).join('');
            return true;
        },
        get(target, key) {
            return target[key].replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
        }
    }
    let phoneNumber = new Proxy({}, phoneHandle);
    phoneNumber.home = '131 1881 2281';
    phoneNumber.work = '159 155 15511';
    console.log(phoneNumber.home);
    console.log(phoneNumber.work);

    const safeHandler = {
        set(target, key, value) {
            const likeKey = Object.keys(target).find(k => k.toLowerCase() === key.toLowerCase());
            if (!(key in target) && likeKey) {
                throw new Error(`Oops! Looks like we already have a property ${key} but with the case of ${likeKey}`);
            }
            target[key] = value;
        }
    };
    const safetyProxy = new Proxy({ id: 2 }, safeHandler);
    safetyProxy.ID = 5;

}